<script setup lang="ts">
import { useDark, useToggle } from '@vueuse/core'
import { inject, ref } from 'vue'
const { getIpLocation, getWeather } = inject('global') as any;
import { useRouter, useRoute } from 'vue-router'
const router = useRouter();
const username = ref(window.localStorage.getItem('username') || '');
const token = ref(window.localStorage.getItem('token') || '');

const isDark = useDark();
const toggleDark = useToggle(isDark);
const province = ref<string>('');
const city = ref<string>('');
const temperature = ref<string>('');
const weather = ref<string>('');

getIpLocation().then((res: any) => {
    province.value = res.province;
    city.value = res.city;
    getWeather(res.adcode).then((result: any) => {
        temperature.value = result.lives[0].temperature;
        weather.value = result.lives[0].weather;
        window.localStorage.setItem('province', result?.lives[0]?.province);
    })
})

const goLogin = () => {
    router.push({
        path: '/login'
    })
}

</script>

<template>
    <div class="header">
        <div class="title">
            TE 的空间
        </div>
        <div class="setting">
            <div class="location">当前位置：{{ province + city }}
                <el-icon>
                    <Location />
                </el-icon>
            </div>
            <el-tooltip effect="dark" :content="temperature + '度 ' + weather" placement="top-start">
                <el-button class="weather">天气：{{ temperature + ' ' + weather }}</el-button>
            </el-tooltip>
            <div class="bgcColor" @click="toggleDark()">
                <el-icon v-if="isDark" :size="26" color="#409EFC">
                    <Sunny />
                </el-icon>
                <el-icon v-else :size="26" color="#409EFC">
                    <Moon />
                </el-icon>
            </div>
            <div v-if="!token || username === ''" class="login" @click="goLogin">登录</div>
            <div v-else class="login">{{ username }}</div>
        </div>
    </div>
</template>

<style scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.header .title {
    font-size: 22px;
    color: #409EFC;
}

.header .setting {
    display: flex;
    align-items: center;
}

.header .setting .location {
    padding-right: 20px;
    font-size: 15px;
}

.header .setting .weather {
    margin-right: 20px;
    font-size: 15px;
}

.header .setting .bgcColor {
    display: flex;
    align-items: center;
    margin-right: 20px;
}

.header .setting .login {
    font-size: 16px;
    color: #409EFC;
    cursor: pointer;
}

.header .setting .bgcColor:hover {
    cursor: pointer;
}
</style>
